package com.projectsexception.festivales.maps.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class MoveImageView extends View {

    private int screenWith = 320;
    private int screenHeight = 480;
    private int scrollX;
    private int scrollY;
    private Bitmap sourceBitmap;
    private Bitmap scaledBitmap;
    private Bitmap showBitmap;
    private float actualZoom;

    public MoveImageView(Context context, Bitmap sourceBitMap) {
        super(context);
        this.sourceBitmap = sourceBitMap;
        this.scaledBitmap = sourceBitMap;
        this.showBitmap = Bitmap.createBitmap(sourceBitMap);
        scrollX = 0;
        scrollY = 0;
        screenWith = getResources().getDisplayMetrics().widthPixels;
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        // FIXME Aproximadamente el espacio para el mapa es el 77%
        screenHeight = (int) (screenHeight - (screenHeight * 0.23));
        actualZoom = 100;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(showBitmap, 0, 0, new Paint());
    }

    public void handleScroll(float distX, float distY) {
        int imageWidth = scaledBitmap.getWidth();
        int imageHeight = scaledBitmap.getHeight();

        scrollX += distX;
        scrollY += distY;
        
        if (scrollX < 0 || imageWidth < screenWith) {
            scrollX = 0;
        } else if (scrollX > imageWidth - screenWith) {
            scrollX = imageWidth - screenWith;
        }
        
        if (scrollY < 0 || imageHeight < screenHeight) {
            scrollY = 0;
        } else if (scrollY > imageHeight - screenHeight) {
            scrollY = imageHeight - screenHeight;
        }
        
        int newWith = imageWidth>screenWith ? screenWith : imageWidth;
        int newHeight = imageHeight>screenHeight ? screenHeight : imageHeight;
        showBitmap = Bitmap.createBitmap(scaledBitmap, scrollX, scrollY, newWith, newHeight);
        invalidate();
    }
    
    public void zoomIn() {
        if (actualZoom < 100) {
            actualZoom += 20;
            resize();
        }
    }
    
    public void zoomOut() {
        if (actualZoom > 20) {
            actualZoom -= 20;
            if (scaledBitmap.getWidth() <= screenWith && scaledBitmap.getHeight() <= screenHeight) {
                actualZoom += 20;
            } else {
                resize();
            }
        }
    }
    
    private void resize() {
        scaledBitmap = Bitmap.createScaledBitmap(sourceBitmap, getNewWidth(), getNewHeight(), true);
        handleScroll(0, 0);
    }
    
    private int getNewWidth() {
        return (int) (sourceBitmap.getWidth() * (actualZoom/100));
    }
    
    private int getNewHeight() {
        return (int) (sourceBitmap.getHeight() * (actualZoom/100));
    }
}
